const fs = require("fs").promises;
const path = require("path");
const recipesPath = path.join(__dirname, "../../db/recipes.json");
const getAll = async () => {
  const data = await fs.readFile(recipesPath, "utf-8");
  return JSON.parse(data);
};
const save = async (recipe) => {
  const recipes = await getAll();
  recipe.id = recipes.length + 1;
  recipes.push(recipe);
  await fs.writeFile(recipesPath, JSON.stringify(recipes));
  return recipe;
};
const get = async (id) => {
  const recipes = await getAll();
  return recipes.find((recipe) => recipe.id === parseInt(id));
};
const update = async (id, updated) => {
  const recipes = await getAll();
  update.id = parseInt(id);
  const updatedRecipes = recipes.map((recipe) => {
    if (recipe.id === id) {
      return updated;
    }
    return recipe;
  });
  await fs.writeFile(recipesPath, JSON.stringify(updatedRecipes));
  return updated;
}
const remove = async (id) => {
  const recipes = await getAll();
  const updatedRecipes = recipes.filter((recipe) => recipe.id !== parseInt(id));
  await fs.writeFile(recipesPath, JSON.stringify(updatedRecipes));
  return updatedRecipes;
};
module.exports = { getAll, save,get,update,remove };
